<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class Adminislogin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $admintoken = $request->header('admintoken');
        $memberinfo = Redis::get($admintoken);

        $memberinfo = $memberinfo ? json_decode($memberinfo, true) : '';

        if (!is_array($memberinfo)) {
            return response()->json([
                'code' => 401, 'msg' => '登录失效，请重新登录!'
            ], 200);
        } else {

            //判断token是否存在于登录token集合
            if (isset($memberinfo['id'])) {
                $admintokenbyidlist = Redis::get('admin_user_token_list_' . $memberinfo['id']);
                $admintokenbyidlist = json_decode($admintokenbyidlist, true);
                if (!is_array($admintokenbyidlist) || !in_array($admintoken, $admintokenbyidlist)) {
                    return response()->json([
                        'code' => 401, 'msg' => '登录失效，请重新登录!!'
                    ], 200);
                }
            } else {
                return response()->json([
                    'code' => 401, 'msg' => '登录失效，请重新登录'
                ], 200);
            }

            $endTime = $request->input('end_time', '');
            if (!empty($endTime)) {
                $request->merge(['end_time' => $this->dateFormat($endTime)]);
            }


            $res = $next($request);

            $content=$res->getContent()?json_decode($res->getContent(),true):'';
            if(is_array($content)){
                if(isset($content['msg'])){
                    if(strpos($content['msg'],'Data too long for column')!==false || strpos($content['msg'],'Out of range value for column')!==false){
                        return response()->json([
                            'code' => '001', 'msg' => '您的输入已超出限制，请重新输入！'
                        ]);
                    }
                }

            }
            return $res;
        }
    }


    /**
     * 时间处理
     * @param $date
     * @return false|int|string
     */
    public function dateFormat($date)
    {
        if (is_numeric($date)) {
            $date = date("Y-m-d", $date);
            $date = sprintf('%s %s', $date, '23:59:59');
            $date = strtotime($date);
        } else {
            $date = sprintf('%s %s', $date, '23:59:59');
        }
        return $date;
    }
}
